import {match} from 'dva-react-router-3/router';
import {createMemoryHistory} from 'history';
import {renderToString} from 'react-dom/server'
import {routes, routeConfig} from '../common/router';
import createApp from '../common/createApp';

function matchSync(opt) {
    return new Promise(function (resolve, reject) {
        match(opt, function (err, redirectLocation, renderProps) {
            if (err) {
                reject(err)
            } else {
                resolve(renderProps)
            }
        })
    }).then(function (res) {
        return res;
    }, function (res) {
        return res;
    })
}

export default async function (ctx, next) {
    let {req, res} = ctx;
    let renderProps = await matchSync({
        routes: routes(),
        location: req.url,
    });
    if (renderProps) {
        let app, html, initialState = {};
        let route;
        routeConfig().some((item) => {
            if (renderProps.location.pathname === item.path) {
                route = item;
                return true;
            }
        })
        if (route && typeof route.syncData == 'function') {
            initialState = await route.syncData();
        }
        app = createApp({
            history: createMemoryHistory(),
            initialState,
        }, /* isServer */true);

        html = renderToString(app.start()({renderProps}));
        // ctx.response.body = renderFullPage(html, initialState);
        await ctx.render('index', {html: html, initialState: JSON.stringify(initialState)})
    }


}

